﻿using AccustomeAttributedll;
using AixCommInfo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FinalTestMachine.View.Dispenser
{
    /// <summary>
    /// Unit_FunAixsButtonViewModel.xaml 的交互逻辑
    /// </summary>
    public partial class Unit_FunAixsButtonViewModel : UserControl
    {
        public Unit_FunAixsButtonViewModel()
        {
            InitializeComponent();
        }

        event Action actionBtnEnableOFF;
        event Action actionBtnEnableON;
        bool IsSet = false;
        public void Setcomponent(object abstractLineThreeAixs)
        {

            if (IsSet) return;
            IsSet = true;
            //=========================================================
            Type type = abstractLineThreeAixs.GetType();

            var memberInfos = type.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(s => s.IsDefined(typeof(ButtonRemarkAttribute), true) == true);

            //开始分组判断：1.默认分组，2.标识分组
            var NoGroupMembers = memberInfos.Where(s => s.IsDefined(typeof(GroupRemarkAttribute), true) == false);
            var RemarkGroupMembers = memberInfos.Where(s => s.IsDefined(typeof(GroupRemarkAttribute), true) == true);
            TabControl table = new TabControl();
            void AddChildrenToWrapPanel(WrapPanel wrapPanel, IEnumerable<MemberInfo> enumerator)
            {
                foreach (var vr in enumerator)
                {
                    if (vr.MemberType == MemberTypes.Field)
                    {
                        FieldInfo fieldInfo = vr as FieldInfo;
                        if (typeof(IMov).IsAssignableFrom(fieldInfo.FieldType))
                        {
                            //ThreeAixsLineMovMsg threeAixsLineMovMsgSouce = fieldInfo.GetValue(abstractLineThreeAixs) as ThreeAixsLineMovMsg;
                            IMov mov = fieldInfo.GetValue(abstractLineThreeAixs) as IMov;
                            //获取按钮信息标识
                            ButtonRemarkAttribute paramRemarkAttribute = (ButtonRemarkAttribute)vr.GetCustomAttributes(typeof(ButtonRemarkAttribute), true)[0];

                            LanCustomControldll.UC_CornerButton unit_UserButtonDemoViewModel = new LanCustomControldll.UC_CornerButton();
                            unit_UserButtonDemoViewModel.LanContent = paramRemarkAttribute.GetRemark();
                            unit_UserButtonDemoViewModel.Margin = new Thickness(10, 10, 10, 10);
                            unit_UserButtonDemoViewModel.Background = paramRemarkAttribute.GetColor();


                            actionBtnEnableOFF += () => unit_UserButtonDemoViewModel.IsEnabled = false;
                            actionBtnEnableON += () => unit_UserButtonDemoViewModel.IsEnabled = true;

                            unit_UserButtonDemoViewModel.btn_1.Click += (s, r) => { SafeBeginInvoke(() => mov.Mov()); };

                            wrapPanel.Children.Add(unit_UserButtonDemoViewModel);
                        }

                    }
                    else if (vr.MemberType == MemberTypes.Method)
                    {
                        MethodInfo methodInfo = vr as MethodInfo;

                        //获取按钮信息标识
                        ButtonRemarkAttribute paramRemarkAttribute = (ButtonRemarkAttribute)vr.GetCustomAttributes(typeof(ButtonRemarkAttribute), true)[0];

                        LanCustomControldll.UC_CornerButton unit_UserButtonDemoViewModel = new LanCustomControldll.UC_CornerButton();
                        unit_UserButtonDemoViewModel.LanContent = paramRemarkAttribute.GetRemark();
                        unit_UserButtonDemoViewModel.Margin = new Thickness(10, 10, 10, 10);
                        unit_UserButtonDemoViewModel.Background = paramRemarkAttribute.GetColor();


                        actionBtnEnableOFF += () => unit_UserButtonDemoViewModel.IsEnabled = false;
                        actionBtnEnableON += () => unit_UserButtonDemoViewModel.IsEnabled = true;
                        unit_UserButtonDemoViewModel.btn_1.Click += (s, r) => { SafeBeginInvoke(() => methodInfo.Invoke(abstractLineThreeAixs, null)); };

                        wrapPanel.Children.Add(unit_UserButtonDemoViewModel);

                    }
                }
            }

            //判断默认分组里面是否含有元素，如果有则创建默认分组页
            if (NoGroupMembers.Count() > 0)
            {
                //创建默认分组页
                TabItem tabItemNoGroup = new TabItem();
                tabItemNoGroup.Header = "默认";
                tabItemNoGroup.FontSize = 15;
                tabItemNoGroup.MinHeight = 20;
                //创建按键的容器
                WrapPanel wrapPanel = new WrapPanel();
                AddChildrenToWrapPanel(wrapPanel, NoGroupMembers);

                //如果没有指示分组，则不需要创建Table
                if (RemarkGroupMembers.Count() > 0)
                {
                    tabItemNoGroup.Content = wrapPanel;
                    table.Items.Add(tabItemNoGroup);

                }
                else
                {
                    gd_1.Children.Add(wrapPanel);

                    return;
                }
            }

            //创建标识分组
            Dictionary<string, List<MemberInfo>> keyValuePairs = new Dictionary<string, List<MemberInfo>>();
            foreach (var vr in RemarkGroupMembers)
            {
                MemberInfo methodInfo = vr as MemberInfo;
                //获取分组信息标识
                GroupRemarkAttribute paramRemarkAttribute = (GroupRemarkAttribute)vr.GetCustomAttributes(typeof(GroupRemarkAttribute), true)[0];
                if (keyValuePairs.Keys.Contains(paramRemarkAttribute.GetRemark()))
                {
                    keyValuePairs[paramRemarkAttribute.GetRemark()].Add(vr);
                }
                else
                {
                    keyValuePairs.Add(paramRemarkAttribute.GetRemark(), new List<MemberInfo>());
                    keyValuePairs[paramRemarkAttribute.GetRemark()].Add(vr);
                }
            }

            foreach (var vr in keyValuePairs.Keys)
            {
                TabItem tabItem = new TabItem();
                tabItem.Header = vr;
                tabItem.Tag = vr;
                tabItem.FontSize = 15;
                tabItem.MinHeight = 20;
                //创建按键的容器
                WrapPanel wrapPanel = new WrapPanel();
                AddChildrenToWrapPanel(wrapPanel, keyValuePairs[vr]);
                tabItem.Content = wrapPanel;
                table.Items.Add(tabItem);
            }
            if (table.Items.Count > 0)
            {
                gd_1.Children.Add(table);

            }

        }
        void SafeBeginInvoke(Action action)
        {
            Action SaveBeginInvokeAction = null;
            void SaveInvoke(Action action1)
            {
                try
                {
                    action1?.Invoke();
                }
                catch (Exception ex)
                {
                    string get(Exception ex1)
                    {
                        if (ex1.InnerException == null)
                        {
                            return ex1.Message;
                            // return;
                        }
                        return get(ex1.InnerException);
                    }

                    this.Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show(get(ex));
                    });
                }
            }

            try
            {

                SaveBeginInvokeAction = () => SaveInvoke(action);
                SaveBeginInvokeAction.BeginInvoke(null, null);
            }
            catch (Exception ex)
            {
                string get(Exception ex1)
                {
                    if (ex1.InnerException == null)
                    {
                        return ex1.Message;
                        // return;
                    }
                    return get(ex1.InnerException);
                }

                this.Dispatcher.Invoke(() =>
                {
                    MessageBox.Show(get(ex));
                });
            }
        }



        public void Button_EnableOFF()
        {

            actionBtnEnableOFF?.Invoke();
        }

        public void Button_EnableON()
        {
            actionBtnEnableON?.Invoke();
        }
    }
}
